<template>
  <div class="role-manage-page pd16" v-loading="pageLoading">
    <el-row :gutter="16" class="flex-block">
      <el-col :span="6">
        <el-card class="box-card sp-card not-padding-card">
          <div class="btn">
            <el-button type="primary" @click="addRole">新增角色</el-button>
          </div>
          <div v-if="roleData.length === 0" class="empty-role">
            <e-icon type="MessageBox" :size="40"></e-icon>
            <div class="empty-text">
              没有数据
            </div>
          </div>
          <div v-else class="role-block mt16">
            <div :class="['role-item', currentRole.roleId === item.roleId ? 'active' : null]" v-for="(item, index) in roleData" :key="index" @click="handleClick(item)">
              <span class="name">{{item.roleName}}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card sp-card">
          <div class="btn-group">
            <el-button type="primary" @click="handleAuth(currentRole)">角色权限</el-button>
            <el-button type="primary" @click="handleEdit(currentRole)">编辑角色</el-button>
            <el-button @click="handleDelete(currentRole)">删除角色</el-button>
          </div>

          <div ref="tableBlockRef" class="data-block mt16 table-block">
            <el-table
              :data="tableData"
              class="nr-table"
              row-key="id"
              :max-height="tableHeight"
              default-expand-all>
              <el-table-column prop="title" label="菜单">
                <template #default="scope">
                  <!-- <span v-if="scope.row.icon" class="menu-icon">
                    <e-icon :type="scope.row.icon" :size="14"></e-icon>
                  </span> -->
                  <span style="vertical-align: top;display: inline-block;">{{scope.row.title}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="auth" label="权限">
                <template #default="scope">
                  <span v-if="scope.row.auth === 1">✔</span>
                  <span v-else-if="scope.row.auth === 0">X</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <role-modify-form
      :dialogVisible="modifyFormVis"
      :formStatus="modifyFormStatus"
      :formData="roleFormData.data"
      @update:dialogVisible="(value: boolean) => modifyFormVis = value"
      @submit="getRoleData">
    </role-modify-form>

    <role-auth-dialog
      :dialogVisible="authDialogVis"
      :formData="roleFormData.data"
      @update:dialogVisible="(value: boolean) => authDialogVis = value"
      @submit="getRoleData">
    </role-auth-dialog>

    <role-select-user-dialog
      :dialogVisible="selectUserDialogVis"
      @update:dialogVisible="(value: boolean) => selectUserDialogVis = value"
      @submit="getRoleData">
    </role-select-user-dialog>
  </div>
</template>

<script setup lang="ts" name="RoleManage">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import EIcon from '@/components/e-icon/e-icon.vue'
import RoleModifyForm from './role-modify-form.vue'
import RoleAuthDialog from './role-auth-dialog.vue'
import RoleSelectUserDialog from './role-select-user-dialog.vue'
import { roleList, roleDelete } from '@/api/role-manage'
import NAV from '@/config/navs'

const pageLoading = ref(false)
const roleData = ref<any>([])
const tableData = ref<any>([])
const tableBlockRef = ref<any>(null)
const tableHeight = ref(200)
const currentRole = reactive({
  roleId: -1,
  roleName: '',
  power: ''
})
const modifyFormVis = ref(false)
const modifyFormStatus = ref(0)
const roleFormData = ref({
  data: {}
})
const authDialogVis = ref(false)
const selectUserDialogVis = ref(false)

onMounted(() => {
  resizeTable()
  window.addEventListener('resize', resizeTable, false)
  tableData.value = [...NAV]
  getRoleData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeTable, false)
})

// 窗口改变table高度
const resizeTable = () => {
  tableHeight.value = tableBlockRef.value.offsetHeight
}

// 生成权限菜单
const buildAuthMenu = (power: any) => {
  if (power) {
    let menu = JSON.parse(power)
    let selected = <any>[]
    menu.map((item: any) => {
      selected.push(item.id)
      item.children.map((cl: any) => {
        selected.push(cl.id)
      })
    })
    let arr = <any>[]
    NAV.map((item: any) => {
      let obj = {
        id: item.id,
        title: item.title,
        index: item.index,
        icon: item.icon,
        children: <any>[],
        auth: 0
      }
      if (selected.indexOf(item.id) !== -1) {
        obj.auth = 1
      }
      item.children.map((cl: any) => {
        if (selected.indexOf(cl.id) !== -1) {
          obj.children.push(Object.assign({ auth: 1 }, cl))
        } else {
          obj.children.push(Object.assign({ auth: 0 }, cl))
        }
      })
      arr.push(obj)
    })
    tableData.value = [...arr]
  } else {
    tableData.value = [...NAV]
  }
}

// 点击角色
const handleClick = (row: any) => {
  currentRole.roleId = row.roleId
  currentRole.roleName = row.roleName
  currentRole.power = row.power
  buildAuthMenu(row.power)
}

// 新建
const addRole = () => {
  modifyFormVis.value = true
  modifyFormStatus.value = 0
}

// 编辑
const handleEdit = (row: any) => {
  if (currentRole.roleId === -1) {
    ElMessage.error(`未选择角色！`)
    return false
  }
  modifyFormVis.value = true
  modifyFormStatus.value = 1
  roleFormData.value.data = Object.assign({}, row)
}

// 角色权限
const handleAuth = (row: any) => {
  if (currentRole.roleId === -1) {
    ElMessage.error(`未选择角色！`)
    return false
  }
  authDialogVis.value = true
  roleFormData.value.data = Object.assign({}, row)
}

// 删除
const handleDelete = (row: any) => {
  if (currentRole.roleId === -1) {
    ElMessage.error(`未选择角色！`)
    return false
  }
  ElMessageBox.confirm(
    `确定要删除【${currentRole.roleName}】此角色吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      roleId: row.roleId
    }
    roleDelete(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`删除成功！`)
        getRoleData()
        currentRole.roleId = -1
        currentRole.roleName = ''
        currentRole.power = ''
        tableData.value = [...NAV]
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 获取角色列表数据
const getRoleData = async () => {
  pageLoading.value = true
  await roleList().then((res: any) => {
    if (res.code === 0) {
      roleData.value = [...res.list]
      if (currentRole.roleId !== -1) {
        res.list.map((item: any) => {
          if (item.roleId === currentRole.roleId) {
            currentRole.roleId = item.roleId
            currentRole.roleName = item.roleName
            currentRole.power = item.power
            buildAuthMenu(item.power)
          }
        })
      }
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.role-manage-page
  height 100%
  .not-padding-card
    &:deep(.el-card__body)
      padding 0px
  .btn
    margin 20px
  .empty-role
    text-align center
    color #888
    padding 16px 0px
    box-sizing border-box
    margin-top 100px
    .empty-text
      font-size 14px
  .role-block
    position absolute
    left 0px
    right 0px
    bottom 0px
    top 50px
    overflow-y auto
    .role-item
      padding 16px
      box-sizing border-box
      cursor pointer
      border-bottom 1px solid #ddd
      display flex
      justify-content space-between
      transition background .2s linear
      .name
        font-size 14px
      &:hover
        background #eee
      &.active
        background #eee
      &:first-child
        border-top 1px solid #ddd
  .menu-icon
    vertical-align middle
    margin-right 4px
    display inline-block
  .table-block
    top 52px
    bottom 16px
</style>
